/**
 * Copyright &copy; 2016-2017 <a href="http://git.oschina.net/whoamien/backend_management">Backend Management</a> All rights reserved.
 */
package com.xw.app.imageupload;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.AbortMultipartUploadRequest;
import com.aliyun.oss.model.CompleteMultipartUploadRequest;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.InitiateMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadResult;
import com.aliyun.oss.model.ListMultipartUploadsRequest;
import com.aliyun.oss.model.MultipartUpload;
import com.aliyun.oss.model.MultipartUploadListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PartETag;
import com.aliyun.oss.model.UploadPartRequest;
import com.aliyun.oss.model.UploadPartResult;

/**
 * The Class OSSManageUtil.
 *
 * @author Xi Wei
 */
public class OSSManageUtil {

	/**
	 * 上传OSS服务器文件 @Title: uploadFile @Description: @param @param
	 * ossConfigure @param @param file @param @param
	 * remotePath @param @return @param @throws Exception 设定文件 @return String
	 * 返回类型 @throws.
	 *
	 * @param ossConfigure the oss configure
	 * @param file the file
	 * @param remotePath the remote path
	 * @return the string
	 * @throws Exception the exception
	 */
	public static String uploadFile(OSSConfigure ossConfigure, File file, String remotePath) throws Exception {
		InputStream fileContent = null;
		fileContent = new FileInputStream(file);

		OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
				ossConfigure.getAccessKeySecret());
		String remoteFilePath = remotePath.substring(0, remotePath.length()).replaceAll("\\\\", "/") + "/";
		// 创建上传Object的Metadata
		ObjectMetadata objectMetadata = new ObjectMetadata();
		objectMetadata.setContentLength(fileContent.available());
		objectMetadata.setCacheControl("no-cache");
		objectMetadata.setHeader("Pragma", "no-cache");
		objectMetadata.setContentType(contentType(file.getName().substring(file.getName().lastIndexOf("."))));
		objectMetadata.setContentDisposition("inline;filename=" + file.getName());
		// 上传文件
		ossClient.putObject(ossConfigure.getBucketName(), remoteFilePath + file.getName(), fileContent, objectMetadata);
		System.out.println(ossConfigure.getAccessUrl() + "/" + remoteFilePath + file.getName());
		return ossConfigure.getAccessUrl() + "/" + remoteFilePath + file.getName();
	}

	/**
	 * 根据key删除OSS服务器上的文件 @Title: deleteFile @Description: @param @param
	 * ossConfigure @param @param filePath 设定文件 @return void 返回类型 @throws.
	 *
	 * @param ossConfigure the oss configure
	 * @param filePath the file path
	 */
	public static void deleteFile(OSSConfigure ossConfigure, String filePath) {
		OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
				ossConfigure.getAccessKeySecret());
		ossClient.deleteObject(ossConfigure.getBucketName(), filePath);

	}

	/**
	 * Description: 判断OSS服务文件上传时文件的contentType @Version1.0
	 * 
	 * @param FilenameExtension
	 *            文件后缀
	 * @return String
	 */
	public static String contentType(String FilenameExtension) {
		if (FilenameExtension.equals("BMP") || FilenameExtension.equals("bmp")) {
			return "image/bmp";
		}
		if (FilenameExtension.equals("GIF") || FilenameExtension.equals("gif")) {
			return "image/gif";
		}
		if (FilenameExtension.equals("JPEG") || FilenameExtension.equals("jpeg") || FilenameExtension.equals("JPG")
				|| FilenameExtension.equals("jpg") || FilenameExtension.equals("PNG")
				|| FilenameExtension.equals("png")) {
			return "image/jpeg";
		}
		if (FilenameExtension.equals("HTML") || FilenameExtension.equals("html")) {
			return "text/html";
		}
		if (FilenameExtension.equals("TXT") || FilenameExtension.equals("txt")) {
			return "text/plain";
		}
		if (FilenameExtension.equals("VSD") || FilenameExtension.equals("vsd")) {
			return "application/vnd.visio";
		}
		if (FilenameExtension.equals("PPTX") || FilenameExtension.equals("pptx") || FilenameExtension.equals("PPT")
				|| FilenameExtension.equals("ppt")) {
			return "application/vnd.ms-powerpoint";
		}
		if (FilenameExtension.equals("DOCX") || FilenameExtension.equals("docx") || FilenameExtension.equals("DOC")
				|| FilenameExtension.equals("doc")) {
			return "application/msword";
		}
		if (FilenameExtension.equals("XML") || FilenameExtension.equals("xml")) {
			return "text/xml";
		}
		return "text/html";
	}

	/**
	 * The main method.
	 *
	 * @param args the arguments
	 */
	public static void main(String[] args) {
		try {
			OSSConfigure config = new OSSConfigure("aliyunoss.properties");
			File file = new File("/opt/aliyun/apache-tomcat-7.0.64/webapps/leyoobao/upload/img/20151030170944909.png");
			// uploadFile(config, file, "aliyun/test");
			int partSize = 1024 * 1024 * 5;
			File partFile = new File("/Users/xiwei/Downloads/QQ_V4.0.4.dmg");
			int partCount = (int) (partFile.length() / partSize);
			if (partFile.length() % partSize != 0) {
				partCount++;
			}
			OSSClient client = new OSSClient(config.getEndpoint(), config.getAccessKeyId(),
					config.getAccessKeySecret());

			// 获取Bucket内所有上传事件
			ListMultipartUploadsRequest listMultipartUploadsRequest = new ListMultipartUploadsRequest(
					config.getBucketName());
			MultipartUploadListing listing = client.listMultipartUploads(listMultipartUploadsRequest);

			// 遍历所有上传事件
			for (MultipartUpload multipartUpload : listing.getMultipartUploads()) {
				System.out.println("Key: " + multipartUpload.getKey() + " UploadId: " + multipartUpload.getUploadId());

				AbortMultipartUploadRequest abortMultipartUploadRequest = new AbortMultipartUploadRequest(
						config.getBucketName(), config.getAccessKeyId(), multipartUpload.getUploadId());
				client.abortMultipartUpload(abortMultipartUploadRequest);
			}

			InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(
					config.getBucketName(), config.getAccessKeyId());
			InitiateMultipartUploadResult initiateMultipartUploadResult = client
					.initiateMultipartUpload(initiateMultipartUploadRequest);
			System.out.println("UploadId: " + initiateMultipartUploadResult.getUploadId());

			List<PartETag> partETags = new ArrayList<PartETag>();
			for (int i = 0; i < partCount; i++) {
				// 获取文件流
				FileInputStream fis = new FileInputStream(partFile);
				// 跳到每个分块的开头
				long skipBytes = partSize * i;
				fis.skip(skipBytes);
				// 计算每个分块的大小
				long size = partSize < partFile.length() - skipBytes ? partSize : partFile.length() - skipBytes;
				// 创建UploadPartRequest，上传分块
				UploadPartRequest uploadPartRequest = new UploadPartRequest();
				uploadPartRequest.setBucketName(config.getBucketName());
				uploadPartRequest.setKey(config.getAccessKeyId());
				uploadPartRequest.setUploadId(initiateMultipartUploadResult.getUploadId());
				uploadPartRequest.setInputStream(fis);
				uploadPartRequest.setPartSize(size);
				uploadPartRequest.setPartNumber(i + 1);
				UploadPartResult uploadPartResult = client.uploadPart(uploadPartRequest);
				// 将返回的PartETag保存到List中。
				partETags.add(uploadPartResult.getPartETag());
				// 关闭文件
				fis.close();
			}

			CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(
					config.getBucketName(), config.getAccessKeyId(), initiateMultipartUploadResult.getUploadId(),
					partETags);
			CompleteMultipartUploadResult completeMultipartUploadResult = client
					.completeMultipartUpload(completeMultipartUploadRequest);

			System.out.println(completeMultipartUploadResult.getETag());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
